package com.itheima.service.impl;

import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.SetmealCheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupCheckItemMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Encounter
 * @date 2024/10/03 18:09<br/>
 */
@Service
@Slf4j
public class CheckGroupServiceImpl implements CheckGroupService
    {
        @Autowired
        private CheckGroupMapper checkGroupMapper;
        @Autowired
        private CheckGroupCheckItemMapper checkGroupCheckItemMapper;
        @Autowired
        private CheckItemMapper checkItemMapper;
        @Autowired
        private SetmealCheckGroupMapper setmealCheckGroupMapper;
        
        /**
         * 新增检查组
         *
         * @param checkItemIds 检查项目 ID
         * @param checkGroup   检查组
         */
        @Override
        @Transactional
        public void add(List<Integer> checkItemIds, CheckGroup checkGroup)
            {
                //插入CheckGroup表
                checkGroupMapper.insert(checkGroup);
                //插入CheckGroupCheckItem表
                insertCheckGroupCheckItem(checkItemIds, checkGroup);
            }
        
        /**
         * 根据id删除
         *
         * @param checkItemIds 检查项目 ID
         */
        @Override
        public void delete(List<Integer> checkItemIds)
            {
                if (!checkItemIds.isEmpty())
                    {
                        for (Integer checkItemId : checkItemIds)
                            {
                                CheckGroup checkGroup = getById(checkItemId);
                                if (checkGroup != null)
                                    {
                                        checkGroupMapper.delete(checkItemIds);
                                    }
                                else
                                    {
                                        throw new RuntimeException(MessageConstant.CHECKGROUP_NOT_EXIST);
                                    }
                            }
                    }
                throw new RuntimeException();
            }
        
        /**
         * 获取由id
         *
         * @param checkGroupId 检查群id
         * @return {@link CheckGroup }
         */
        @Override
        public CheckGroup getById(Integer checkGroupId)
            {
                //根据id获取检查组信息
                CheckGroup checkGroup = checkGroupMapper.getById(checkGroupId);
                
                //获取检查组关联的检查项信息
                List<Integer> checkItemIds = checkGroupCheckItemMapper.findCheckItemIdsByCheckGroupId(checkGroupId);
                if (!checkItemIds.isEmpty())
                    {
                        List<CheckItem> checkItemList = new ArrayList<>();
                        for (Integer checkItemId : checkItemIds)
                            {
                                CheckItem checkItem = checkItemMapper.queryById(checkItemId);
                                checkItemList.add(checkItem);
                            }
                        checkGroup.setCheckItems(checkItemList);
                    }
                return checkGroup;
            }
        
        /**
         * 修改checkGroup
         *
         * @param checkGroup 检查组
         */
        @Override
        @Transactional
        public void update(CheckGroup checkGroup)
            {
                //检查要修改的表是否存在
                Integer id = checkGroup.getId();
                CheckGroup checkGroupTest = getById(id);
                if (checkGroupTest == null)
                    {
                        throw new RuntimeException(MessageConstant.CHECKGROUP_NOT_EXIST);
                    }
                //修改checkGroup表
                checkGroupMapper.update(checkGroup);
                
                //修改关联的检查项信息
                List<CheckItem> checkItems = checkGroup.getCheckItems();
                if (checkItems != null && !checkItems.isEmpty())
                    {
                        //直接删除中间表中当前检查组关联的所有检查项
                        checkGroupCheckItemMapper.deleteByCheckGroupId(checkGroup.getId());
                        //便利添加新的关联关系
                        //先得到要插入的检查项的id集合
                        List<Integer> checkItemIds = new ArrayList<>();
                        for (CheckItem checkItem : checkItems)
                            {
                                checkItemIds.add(checkItem.getId());
                            }
                        //插入中间表
                        insertCheckGroupCheckItem(checkItemIds, checkGroup);
                    }
            }
        
        /**
         * 分页查询
         *
         * @param queryPageBean 查询页面 Bean
         * @return {@link PageResult }
         */
        @Override
        public PageResult queryPage(QueryPageBean queryPageBean)
            {
                //解析查询条件
                String queryString = queryPageBean.getQueryString();
                Map<String, Object> queryStringMap = parseQueryConditions(queryString);
                log.info("queryStringMap: {}", queryStringMap);
                
                //设置分页参数
                PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
                
                //开始查询
                List<CheckGroup> checkGroupList = checkGroupMapper.query(queryStringMap);
                //将检查项信息查询出来封装到checkGroupList
                for (CheckGroup checkGroup : checkGroupList)
                    {
                        BeanUtils.copyProperties(getById(checkGroup.getId()), checkGroup);
                    }
                //log.info("checkGroupList:{}",checkGroupList);
                Page<CheckGroup> page = (Page<CheckGroup>) checkGroupList;
                if (page.getResult() != null && !page.getResult().isEmpty())
                    {
                        return new PageResult(page.getTotal(), page.getResult());
                    }
                //查询结果为空
                throw new RuntimeException(MessageConstant.CHECKGROUP_NOT_EXIST);
            }
        
        /**
         * 查找全部
         *
         * @return {@link List }<{@link CheckGroup }>
         */
        @Override
        public List<CheckGroup> findAll()
            {
                //传入一个空集合，即无查询条件，直接查询全部
                List<CheckGroup> checkGroupList = checkGroupMapper.query(new HashMap<>());
                if (checkGroupList != null && !checkGroupList.isEmpty())
                    {
                        //将检查项信息查询出来封装到checkGroupList
                        for (CheckGroup checkGroup : checkGroupList)
                            {
                                BeanUtils.copyProperties(getById(checkGroup.getId()), checkGroup);
                            }
                    }
                return checkGroupList;
            }
        
        /**
         * 找到检查群IDS由套餐id
         *
         * @param setmealId 套餐id
         * @return {@link List }<{@link Integer }>
         */
        @Override
        public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId)
            {
                return setmealCheckGroupMapper.findCheckGroupIdsBySetmealId(setmealId);
            }
        
        /**
         * 插入中间表 CheckGroupCheckItem
         *
         * @param checkItemIds 检查项目 ID
         * @param checkGroup   检查组
         */
        private void insertCheckGroupCheckItem(List<Integer> checkItemIds, CheckGroup checkGroup)
            {
                if (checkItemIds != null && !checkItemIds.isEmpty())
                    {
                        Map<String, Integer> map = new HashMap<>();
                        map.put("checkGroupId", checkGroup.getId());
                        for (Integer checkItemId : checkItemIds)
                            {
                                map.put("checkItemId", checkItemId);
                                log.info("map:{}", map);
                                checkGroupCheckItemMapper.insert(map);
                            }
                    }
            }
        
        /**
         * 解析查询条件<br>
         * 查询条件格式示例："queryString":"name:路明非;code:22"<br>
         * 注意：所有符号均为引英文状态下
         *
         * @param queryConditions 查询条件
         * @return {@link Map }<{@link String },{@link Object }>
         */
        public Map<String, Object> parseQueryConditions(String queryConditions)
            {
                //创建map集合封装查询条件
                Map<String, Object> map = new HashMap<>();
                //以“;”分割每个查询条件
                String[] conditions = queryConditions.split(";");
                for (String condition : conditions)
                    {
                        //以“:”分割每个查询条件的key与value
                        String[] keyValue = condition.split(":");
                        if (keyValue.length == 2)
                            {
                                map.put(keyValue[0], keyValue[1]);
                            }
                    }
                return map;
            }
    }
